/*
 * Copyright (c) 2011 duowan.com. 
 * All Rights Reserved.
 * This program is the confidential and proprietary information of 
 * duowan. ("Confidential Information").  You shall not disclose such
 * Confidential Information and shall use it only in accordance with
 * the terms of the license agreement you entered into with duowan.com.
 */
package com.superhelper.common.mapper;

import java.util.Date;
import java.util.List;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.springframework.dao.DataAccessException;

import com.superhelper.common.domain.Task;

public interface TaskMapper {

    /**
     * @param retryMaxTimes
     * @param i
     * @return
     * @throws DataAccessException
     */
    @Select("select * from task_print where flag = 0 and nextTime <= current_timestamp and retryTimes <= #{retryMaxTimes} limit #{limit}")
    List<Task> getExcutableTask(@Param("retryMaxTimes") int retryMaxTimes, @Param("limit") int limit);

    /**
     * @param id
     * @param retryTimes
     * @return
     * @throws DataAccessException
     */
    @Update("update task_print set flag=1 where id= #{id} and retryTimes = #{retryTimes} and flag=0")
    int occupyTask(@Param("id") Long id, @Param("retryTimes") Integer retryTimes);

    /**
     * @param id
     * @return
     */
    @Delete("delete from task_print where id = #{value}")
    int deleteTask(Long id);

    /**
     * @param id
     * @param nextTime
     * @return
     */
    @Update("update task_print set nextTime = #{nextTime}, flag=0 , retryTimes = retryTimes+1 where id=#{id} and flag=1")
    int delayTask(@Param("id") Long id, @Param("nextTime") Date nextTime);

    /**
     * @param task
     */
    @Insert("insert into task_print(`type`,objId,flag,retryTimes,nextTime,createTime)values(#{type},#{objId},#{flag},#{retryTimes},#{nextTime},current_timestamp)")
    boolean addTask(Task task);

    @Select("select count(1) from task_print where `type`=#{type} and objId=#{objId}")
    int hasTask(@Param("type") String type, @Param("objId") String objId);

}
